﻿
using System;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace WCYCReader.ViewModels
{
    public class StringToImageSource : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object obj;
            try
            {
                BitmapImage bitmapImage = new BitmapImage();
                string str = (string)value;
                using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!userStoreForApplication.FileExists(str))
                    {
                        Uri uri = new Uri(str, UriKind.RelativeOrAbsolute);
                        bitmapImage.SetSource(Application.GetResourceStream(uri).Stream);
                    }
                    else
                    {
                        using (IsolatedStorageFileStream isolatedStorageFileStream = userStoreForApplication.OpenFile(str, FileMode.Open, FileAccess.Read))
                        {
                            bitmapImage.SetSource(isolatedStorageFileStream);
                        }
                    }
                    obj = bitmapImage;
                }
            }
            catch
            {
                obj = null;
            }
            return obj;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}

